#!/usr/bin/env node

const { spawn } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const http = require('http');

// 读取配置
let config = {
  port: 3001,
  clientPort: 3000,
  uploadDir: path.join(os.homedir(), 'sucai')
};

if (fs.existsSync('config.json')) {
  try {
    config = { ...config, ...JSON.parse(fs.readFileSync('config.json', 'utf8')) };
  } catch (error) {
    console.log('⚠️ 配置文件读取失败，使用默认配置');
  }
}

// 获取本机IP地址
function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const interface of interfaces[name]) {
      if (interface.family === 'IPv4' && !interface.internal) {
        return interface.address;
      }
    }
  }
  return 'localhost';
}

// 检查端口是否可用
function isPortAvailable(port) {
  return new Promise((resolve) => {
    const server = require('net').createServer();
    server.listen(port, (err) => {
      if (err) {
        resolve(false);
      } else {
        server.once('close', () => resolve(true));
        server.close();
      }
    });
    server.on('error', () => resolve(false));
  });
}

// 寻找可用端口
async function findAvailablePort(startPort) {
  let port = startPort;
  while (!(await isPortAvailable(port))) {
    port++;
  }
  return port;
}

// 检查服务器是否启动
function checkServerHealth(port, maxRetries = 30) {
  return new Promise((resolve, reject) => {
    let retries = 0;
    
    const check = () => {
      const req = http.get(`http://localhost:${port}/api/health`, (res) => {
        if (res.statusCode === 200) {
          resolve(port);
        } else {
          retry();
        }
      });
      
      req.on('error', () => {
        retry();
      });
      
      req.setTimeout(1000, () => {
        req.destroy();
        retry();
      });
    };
    
    const retry = () => {
      retries++;
      if (retries < maxRetries) {
        setTimeout(check, 1000);
      } else {
        reject(new Error('服务器启动超时'));
      }
    };
    
    check();
  });
}

// 显示启动信息
function displayStartupInfo(backendPort, frontendPort, localIP) {
  console.clear();
  
  // 创建醒目的边框
  const width = 70;
  const doubleLine = '█'.repeat(width);
  
  console.log('\n');
  console.log(`\x1b[46m\x1b[30m${doubleLine}\x1b[0m`);
  console.log(`\x1b[46m\x1b[30m█${' '.repeat(width-2)}█\x1b[0m`);
  console.log(`\x1b[46m\x1b[30m█${' '.repeat(22)}📱💻 文件传输工具${' '.repeat(22)}█\x1b[0m`);
  console.log(`\x1b[46m\x1b[30m█${' '.repeat(26)}启动成功！${' '.repeat(26)}█\x1b[0m`);
  console.log(`\x1b[46m\x1b[30m█${' '.repeat(width-2)}█\x1b[0m`);
  console.log(`\x1b[46m\x1b[30m${doubleLine}\x1b[0m`);
  
  console.log('\n');
  
  // 显示访问地址 - 手机端地址最醒目
  console.log('\x1b[43m\x1b[30m╔═══════════════════════════════════════════════════════════════════╗\x1b[0m');
  console.log('\x1b[43m\x1b[30m║                                                                   ║\x1b[0m');
  console.log('\x1b[43m\x1b[30m║                        📱 手机端访问地址                          ║\x1b[0m');
  console.log('\x1b[43m\x1b[30m║                                                                   ║\x1b[0m');
  console.log('\x1b[43m\x1b[30m║' + `     http://${localIP}:${frontendPort}`.padEnd(65) + '║\x1b[0m');
  console.log('\x1b[43m\x1b[30m║                                                                   ║\x1b[0m');
  console.log('\x1b[43m\x1b[30m║   👆 请在手机浏览器中输入上面的地址访问文件传输工具               ║\x1b[0m');
  console.log('\x1b[43m\x1b[30m║                                                                   ║\x1b[0m');
  console.log('\x1b[43m\x1b[30m╚═══════════════════════════════════════════════════════════════════╝\x1b[0m');
  
  console.log('\n');
  
  // 电脑端地址（次要显示）
  console.log('\x1b[36m┌─────────────────────────────────────────────────────────────────┐\x1b[0m');
  console.log('\x1b[36m│                        💻 电脑端访问地址                        │\x1b[0m');
  console.log('\x1b[36m│                                                                 │\x1b[0m');
  console.log(`\x1b[36m│     http://localhost:${frontendPort}`.padEnd(67) + '\x1b[36m│\x1b[0m');
  console.log('\x1b[36m│                                                                 │\x1b[0m');
  console.log('\x1b[36m└─────────────────────────────────────────────────────────────────┘\x1b[0m');
  
  console.log('\n');
  
  // 使用说明
  console.log('\x1b[32m📋 使用说明：\x1b[0m');
  console.log('\x1b[32m   1. 确保手机和电脑连接到同一个WiFi网络\x1b[0m');
  console.log('\x1b[32m   2. 在手机浏览器中输入上面的手机端地址\x1b[0m');
  console.log('\x1b[32m   3. 选择传输模式：上传、发送或接收文件\x1b[0m');
  console.log('\x1b[32m   4. 推荐使用Chrome浏览器获得最佳体验\x1b[0m');
  
  console.log('\n');
  
  // 系统信息
  console.log('\x1b[90m🔧 系统信息：\x1b[0m');
  console.log(`\x1b[90m   后端端口: ${backendPort}\x1b[0m`);
  console.log(`\x1b[90m   前端端口: ${frontendPort}\x1b[0m`);
  console.log(`\x1b[90m   本机IP: ${localIP}\x1b[0m`);
  console.log(`\x1b[90m   上传目录: ${config.uploadDir}\x1b[0m`);
  
  console.log('\n');
  console.log('\x1b[31m按 Ctrl+C 停止服务\x1b[0m');
  console.log('\n' + '─'.repeat(70));
}

// 启动服务
async function startServices() {
  try {
    console.log('🚀 正在启动双向文件传输工具...\n');
    
    // 检查依赖
    if (!fs.existsSync('node_modules')) {
      console.log('❌ 未找到依赖包，请先安装：');
      console.log('   npm install');
      process.exit(1);
    }
    
    // 获取本机IP
    const localIP = getLocalIP();
    console.log(`📡 检测到本机IP: ${localIP}`);
    
    // 寻找可用端口
    console.log('🔍 检查端口可用性...');
    const backendPort = await findAvailablePort(config.port);
    const frontendPort = await findAvailablePort(config.clientPort);
    
    if (backendPort !== config.port) {
      console.log(`⚠️ 端口 ${config.port} 被占用，使用端口 ${backendPort}`);
      // 更新配置文件
      config.port = backendPort;
      fs.writeFileSync('config.json', JSON.stringify(config, null, 2));
    }
    
    if (frontendPort !== config.clientPort) {
      console.log(`⚠️ 端口 ${config.clientPort} 被占用，使用端口 ${frontendPort}`);
      config.clientPort = frontendPort;
      fs.writeFileSync('config.json', JSON.stringify(config, null, 2));
    }
    
    const isWindows = os.type() === 'Windows_NT';
    const npmCmd = isWindows ? 'npm.cmd' : 'npm';
    
    // 启动后端服务
    console.log('🔧 启动后端服务...');
    const backend = spawn(npmCmd, ['run', 'server'], {
      stdio: ['inherit', 'pipe', 'pipe'],
      shell: isWindows,
      env: { ...process.env, PORT: backendPort }
    });
    
    // 等待后端启动
    await checkServerHealth(backendPort);
    console.log('✅ 后端服务启动成功');
    
    // 启动前端服务
    console.log('🔧 启动前端服务...');
    const frontend = spawn(npmCmd, ['run', 'client'], {
      stdio: ['inherit', 'pipe', 'pipe'],
      shell: isWindows,
      env: { ...process.env, PORT: frontendPort }
    });
    
    // 等待前端启动
    await new Promise((resolve, reject) => {
      const timeout = setTimeout(() => {
        reject(new Error('前端服务启动超时'));
      }, 30000);
      
      frontend.stdout.on('data', (data) => {
        const output = data.toString();
        if (output.includes('Local:') || output.includes('localhost') || output.includes('ready in')) {
          clearTimeout(timeout);
          resolve();
        }
      });
      
      frontend.stderr.on('data', (data) => {
        const error = data.toString();
        // Vite的一些警告信息是正常的，不需要当作错误
        if (!error.includes('warning') && !error.includes('deprecated')) {
          console.log('前端信息:', error);
        }
      });
    });
    
    console.log('✅ 前端服务启动成功');
    
    // 显示启动信息
    displayStartupInfo(backendPort, frontendPort, localIP);
    
    // 处理退出信号
    process.on('SIGINT', () => {
      console.log('\n\n🛑 正在停止服务...');
      backend.kill();
      frontend.kill();
      process.exit(0);
    });
    
    process.on('SIGTERM', () => {
      backend.kill();
      frontend.kill();
      process.exit(0);
    });
    
    // 监听子进程退出
    backend.on('exit', (code) => {
      if (code !== 0) {
        console.log(`❌ 后端服务异常退出，代码: ${code}`);
        frontend.kill();
        process.exit(1);
      }
    });
    
    frontend.on('exit', (code) => {
      if (code !== 0) {
        console.log(`❌ 前端服务异常退出，代码: ${code}`);
        backend.kill();
        process.exit(1);
      }
    });
    
  } catch (error) {
    console.error('❌ 启动失败:', error.message);
    process.exit(1);
  }
}

// 启动服务
startServices(); 